//*********************************************************
//
//    Copyright (c) Microsoft. All rights reserved.
//    This code is licensed under the Apache License, Version 2.0.
//    THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
//    ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
//    IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
//    PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//
//*********************************************************

namespace Microsoft.Research.ScientificWorkflow.UIDesigner.ActivityImportWizards
{
    using System;
    using System.IO;
    using System.Windows;
    using System.Windows.Input;
    using Microsoft.Research.ScientificWorkflow.TridentModel;
    using Microsoft.Research.ScientificWorkflow.TridentUtilities;
    using System.Threading;

    /// <summary>
    /// 
    /// </summary>
    public partial class WSActivitySelection : IActivityWizardScreens
    {
        private WSWizardPresenter WSPresenter;
        private bool isDirty;

        public WSActivitySelection(IActivityPresenter presenter)
        {
            this.InitializeComponent();

            WSPresenter = presenter as WSWizardPresenter;

            // Update the Model.
            this.DataContext = WSPresenter.WSModel;

            // Initailize all variables.
            WSPresenter.Initialize();
            this.wsdlUri.TextChanged += new System.Windows.Controls.TextChangedEventHandler(wsdlUri_TextChanged);
        }

        void wsdlUri_TextChanged(object sender, System.Windows.Controls.TextChangedEventArgs e)
        {
            this.connectBtn.IsEnabled = string.IsNullOrEmpty(this.wsdlUri.Text) ? false : true;
        }

        /// <summary>
        /// Called when [click next].
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The <see cref="System.Windows.RoutedEventArgs"/> instance containing the event data.</param>
        private void OnClickNext(object sender, RoutedEventArgs e)
        {
            if (null != NextButtonEventHandler)
            {
                // Read available activity categories.
                WSPresenter.GetActivityCategories();
                NextButtonEventHandler(sender, new ActivityImportEventArgs((new WSActivityCustomization(WSPresenter))));
            }
        }

        /// <summary>
        /// Called when [click back].
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The <see cref="System.Windows.RoutedEventArgs"/> instance containing the event data.</param>
        private void OnClickBack(object sender, RoutedEventArgs e)
        {
            if (null != BackButtonEventHandler)
            {
            }
        }

        /// <summary>
        /// Called when [click cancel].
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The <see cref="System.Windows.RoutedEventArgs"/> instance containing the event data.</param>
        private void OnClickCancel(object sender, RoutedEventArgs e)
        {
            if (null != CancelButtonEventHandler)
            {
                if (!isDirty)
                {
                    CancelButtonEventHandler(sender, e);
                }
                else
                {
                    if (TridentMessageBox.ShowTridentConfirmationYesNoMessageBox(
                        TridentResourceManager.GetString("WizardCloseMessage")) == System.Windows.MessageBoxResult.Yes)

                        CancelButtonEventHandler(sender, e);
                }
            }
        }

        /// <summary>
        /// Called when [click connect].
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The <see cref="System.Windows.RoutedEventArgs"/> instance containing the event data.</param>
        private void OnClickConnect(object sender, RoutedEventArgs e)
        {
            // Get the current cursor.
            Cursor currentCursor = this.Cursor;
            this.Cursor = Cursors.Wait;

            isDirty = true;

            // Reset variables.
            WSPresenter.ResetConnect();

            // Disable the next screen button
            this.nextBtn.IsEnabled = false;

            if(!Uri.IsWellFormedUriString(this.wsdlUri.Text, UriKind.RelativeOrAbsolute))
            {
                TridentMessageBox.ShowTridentErrorMessageBox("Given URL is not in a valid format.");

                // Set the cursor back.
                this.Cursor = currentCursor;

                return;
            }

            // Get the URL
            if (WSPresenter.CheckSystemTools())
            {
                // Temp Path for Web service Activity.
                WebServiceWizardModel.TempPath =
                    Path.Combine(
                    Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
                                              UIDesignerCodeConstants.ACTIVITYTEMPPATH);

                if (!Directory.Exists(WebServiceWizardModel.TempPath))
                {
                    Directory.CreateDirectory(WebServiceWizardModel.TempPath);
                }

                // Start proxy creation on different thread. 
                // It will avoid application hang for more then 30 sec.
                ParameterizedThreadStart pts = new ParameterizedThreadStart(WSPresenter.GenerateProxy);
                Thread newThread = new Thread(pts);
                newThread.Start(this.wsdlUri.Text);

                newThread.Join(1000 * 30);

                // Create the proxy from wsdl path.
                if (File.Exists(WebServiceWizardModel.ProxyTempPath))
                {
                    // Use this proxy to get all WebMthods and Params.
                    if (WSPresenter.GetAvailableWebMethods(WebServiceWizardModel.ProxyTempPath))
                    {
                        this.nextBtn.IsEnabled = true;
                    }
                }

                // Update the Model.
                this.DataContext = WSPresenter.WSModel;

                // Set the cursor back.
                this.Cursor = currentCursor;
            }
        }

        #region IActivityWizardScreens Members

        /// <summary>
        /// Occurs when [Next button handler].
        /// </summary>
        public event EventHandler<ActivityImportEventArgs> NextButtonEventHandler;

        /// <summary>
        /// Occurs when [Back button handler].
        /// </summary>
        public event EventHandler BackButtonEventHandler;

        /// <summary>
        /// Occurs when [Cancel button handler].
        /// </summary>
        public event EventHandler CancelButtonEventHandler;

        /// <summary>
        /// Handles move request.
        /// </summary>
        public event EventHandler OnWindowMoveEventHandler;

        #endregion

        /// <summary>
        /// Called when mouse left button down.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The <see cref="System.Windows.Input.MouseButtonEventArgs"/> instance containing the event data.</param>
        private void OnMouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            if (this.OnWindowMoveEventHandler != null)
            {
                this.OnWindowMoveEventHandler(sender, e);
            }
        }
    }
}